//
//  UIButtonExtensions.swift
//  Fangxukanghan
//
//  Created by 常超群的MacBookPro on 2021/3/22.
//

import UIKit

// MARK: UIButton TapHandler
public extension UIButton {
    func ccq_tapHandler(_ closure: @escaping CCQVoidClosure) { ccq_addTarget { _ in closure() } }
    func ccq_addTarget(for event: UIControl.Event = .touchUpInside, closure: @escaping (UIButton) -> Void) {
        targetClosure = closure
        addTarget(self, action: #selector(UIButton.closureAction), for: event)
    }
    private struct AssociatedKeys { static var targetClosure = "targetClosure" }
    private class ClosureWrapper: NSObject {
        let closure: (UIButton) -> Void
        init(_ closure: @escaping (UIButton) -> Void) { self.closure = closure }
    }
    @objc private func closureAction() { targetClosure?(self) }
    private var targetClosure: ((UIButton) -> Void)? {
        get { return (objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper)?.closure }
        set {
            guard let newValue = newValue else { return }
            objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    ///左文字右图
    func ccq_leftTextAndRightImage(spacing: CGFloat) {
        guard let imageSize = imageView?.image?.size,
              let text = titleLabel?.text,
              let font = titleLabel?.font else { return }
        let insetAmount = spacing / 2
        let titleSize = text.size(withAttributes: [.font: font])
        imageEdgeInsets = UIEdgeInsets(top: 0, left: titleSize.width + insetAmount, bottom: 0, right: -(titleSize.width + insetAmount))
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width + insetAmount), bottom: 0, right: imageSize.width + insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}
